package com.lzm.one.utils;

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.webmasters.WebmastersScopes;

import java.io.FileReader;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author LiZhiMin
 * @Date 2025/1/13 16:23
 */

public class GoogleOAuthExample {

    private static final String CLIENT_SECRET_FILE = "path/to/your/credentials.json";  // 请替换为实际的文件路径
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final List<String> SCOPES = Arrays.asList(WebmastersScopes.WEBMASTERS_READONLY);
    private static final String APPLICATION_NAME = "Your Application Name";

    public static Credential authorize() throws IOException, GeneralSecurityException {
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JSON_FACTORY,
                new FileReader(CLIENT_SECRET_FILE),
                SCOPES)
                .setAccessType("offline")  // 可以使得访问令牌长期有效
                .build();

        // 启动浏览器，用户通过 Google 登录授权
        AuthorizationCodeInstalledApp authApp = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver());
        return authApp.authorize("user");
    }

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        // 获取授权凭证
        Credential credential = authorize();
        // 访问令牌
        String accessToken = credential.getAccessToken();
        System.out.println("Access Token: " + accessToken);
    }
}   